<template>
  <el-dialog
    :title="isAdd ? '新增数据集' : '编辑数据集'"
    v-model="dialogVisible"
    width="650px"
       :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      :disabled="formLoading"
    >
      <el-divider content-position="left">基本信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="数据集名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入数据集名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="数据源" prop="data_source_id">
            <el-select v-model="formData.data_source_id" placeholder="请选择数据源" style="width: 100%"
              @change="handleDataSourceChange"
              :disabled="!isAdd">
              <el-option
                v-for="item in dataSourceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-if="!isAdd" class="field-hint">编辑模式下不可修改数据源</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="表/视图" prop="source_object">
            <el-select
              v-model="formData.source_object"
              placeholder="请选择表或视图"
              style="width: 100%"
              :disabled="!formData.data_source_id || !isAdd"
              filterable
            >
              <el-option-group label="表">
                <el-option
                  v-for="item in tableOptions"
                  :key="'table-' + item.name"
                  :label="item.name"
                  :value="'table:' + item.name"
                />
              </el-option-group>
              <el-option-group label="视图">
                <el-option
                  v-for="item in viewOptions"
                  :key="'view-' + item.name"
                  :label="item.name"
                  :value="'view:' + item.name"
                />
              </el-option-group>
            </el-select>
            <span v-if="!isAdd" class="field-hint">编辑模式下不可修改表/视图</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="category">
            <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="活跃" value="active" />
              <el-option label="未激活" value="inactive" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="标签" prop="tags">
            <el-tag
              v-for="tag in tagList"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleTagClose(tag)"
              style="margin-right: 5px; margin-bottom: 5px;"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="tagInputVisible"
              ref="tagInputRef"
              v-model="tagInputValue"
              class="tag-input"
              size="small"
              @keyup.enter="handleTagConfirm"
              @blur="handleTagConfirm"
            />
            <el-button v-else size="small" @click="showTagInput">
              <el-icon><Plus /></el-icon> 添加标签
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入数据集描述"
            />
          </el-form-item>
        </el-col>
      </el-row>
    <div style="display: none;">
      <el-divider content-position="left">刷新设置</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="启用同步" prop="sync_enabled">
            <el-switch v-model="formData.sync_enabled" />
            <span class="setting-hint">是否启用数据自动同步</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.sync_enabled">
          <el-form-item label="同步频率" prop="sync_frequency">
            <el-select v-model="formData.sync_frequency" placeholder="请选择同步频率" style="width: 100%">
              <el-option label="手动同步" value="manual" />
              <el-option label="每小时" value="hourly" />
              <el-option label="每日" value="daily" />
              <el-option label="每周" value="weekly" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">高级设置</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="同步类型" prop="sync_type">
            <el-select v-model="formData.sync_type" placeholder="请选择同步类型" style="width: 100%">
              <el-option label="全量同步" value="full" />
              <el-option label="增量同步" value="incremental" />
            </el-select>
            <span class="setting-hint">增量同步只更新新增或变更的数据</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.sync_type === 'incremental'">
          <el-form-item label="增量字段" prop="incremental_field">
            <el-select
              v-model="formData.incremental_field"
              placeholder="请选择用于增量同步的字段"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="field in incrementalFieldOptions"
                :key="field.value"
                :label="field.label"
                :value="field.value"
              />
            </el-select>
            <span class="setting-hint">通常选择更新时间、创建时间等时间戳字段</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="变更策略" prop="structure_change_strategy">
            <el-select v-model="formData.structure_change_strategy" placeholder="请选择结构变更处理策略" style="width: 100%">
              <el-option label="通知" value="notify" />
              <el-option label="自动应用" value="auto_apply" />
              <el-option label="忽略" value="ignore" />
            </el-select>
            <span class="setting-hint">当数据源结构发生变化时的处理方式</span>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="formLoading">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, defineProps, defineEmits, watch, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getDatasetDetail, createDataset, updateDataset, syncDatasetFields } from '@/api/dataset'
import { getDataSourceList, getDataSourceObjects, getTableColumns } from '@/api/datasource'

const props = defineProps({
  modelValue: Boolean,
  datasetId: [String, Number],
  isAdd: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 判断是否为新增模式
const isAdd = computed(() => props.isAdd)

// 表单引用
const formRef = ref(null)
const formLoading = ref(false)
const dataSourceOptions = ref([])
const tableOptions = ref([])
const viewOptions = ref([])
const incrementalFieldOptions = ref([])

// 标签相关
const tagList = ref([])
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const tagInputRef = ref(null)

// 分类选项
const categoryOptions = [
  { label: '业务数据', value: '业务数据' },
  { label: '系统数据', value: '系统数据' },
  { label: '其他', value: '其他' }
]

// 表单数据
const formData = reactive({
  name: '',
  data_source_id: '',
  source_object: '',
  type: 'table',
  original_name: '',
  custom_query: '',
  category: '',
  status: 'active',
  tags: '',
  description: '',

  // 同步配置
  sync_enabled: true,
  sync_frequency: 'daily',
  sync_type: 'full',
  incremental_field: '',

  // 结构变更处理
  structure_change_strategy: 'notify'
})

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入数据集名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  data_source_id: [
    { required: true, message: '请选择数据源', trigger: 'change' }
  ],
  source_object: [
    { required: true, message: '请选择表或视图', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  sync_frequency: [
    { required: true, message: '请选择同步频率', trigger: 'change' }
  ],
  sync_type: [
    { required: true, message: '请选择同步类型', trigger: 'change' }
  ],
  incremental_field: [
    {
      required: true,
      message: '增量同步时必须选择增量字段',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (formData.sync_type === 'incremental' && !value) {
          callback(new Error('增量同步时必须选择增量字段'));
        } else {
          callback();
        }
      }
    }
  ],
  structure_change_strategy: [
    { required: true, message: '请选择结构变更处理策略', trigger: 'change' }
  ]
}

// 加载数据源列表
const loadDataSources = async () => {
  try {
    const res = await getDataSourceList()
    if (res && res.items) {
      dataSourceOptions.value = res.items.map(item => ({
        label: item.name,
        value: item.id
      }))
    }
  } catch (error) {
    console.error('获取数据源列表失败:', error)
    ElMessage.error('获取数据源列表失败: ' + (error.message || '未知错误'))
  }
}

// 加载数据源表和视图
const loadSourceObjects = async (dataSourceId) => {
  if (!dataSourceId) return

  try {
    // 加载表
    const tableRes = await getDataSourceObjects(dataSourceId, { object_type: 'table' })
    tableOptions.value = tableRes.data || []

    // 加载视图
    const viewRes = await getDataSourceObjects(dataSourceId, { object_type: 'view' })
    viewOptions.value = viewRes.data || []
  } catch (error) {
    console.error('获取数据源对象失败:', error)
    ElMessage.error('获取数据源对象失败: ' + (error.message || '未知错误'))
  }
}

// 加载表结构
const loadTableColumns = async (dataSourceId, tableName) => {
  if (!dataSourceId || !tableName) return

  try {
    const res = await getTableColumns(dataSourceId, tableName)
    incrementalFieldOptions.value = (res.data || [])
      .filter(col => ['date', 'timestamp', 'datetime'].includes(col.data_type.toLowerCase()))
      .map(col => ({
        label: col.name,
        value: col.name
      }))
  } catch (error) {
    console.error('获取表结构失败:', error)
    ElMessage.error('获取表结构失败: ' + (error.message || '未知错误'))
  }
}

// 处理数据源变更
const handleDataSourceChange = async (value) => {
  if (isAdd.value) {
    formData.source_object = ''
  }
  formData.incremental_field = ''
  await loadSourceObjects(value)
}

// 监听表/视图变更
watch(() => formData.source_object, async (newVal) => {
  if (newVal && formData.data_source_id) {
    const parts = newVal.split(':')
    if (parts.length === 2) {
      const tableName = parts[1]
      await loadTableColumns(formData.data_source_id, tableName)
    }
  } else {
    incrementalFieldOptions.value = []
  }
})

// 初始化数据
const initFormData = async () => {
  if (props.datasetId) {
    formLoading.value = true
    try {
      var re = await getDatasetDetail(props.datasetId)
      const res=re.data
      Object.assign(formData, {
        name: res.name,
        data_source_id: res.data_source_id,
        category: res.category || '',
        description: res.description || '',
        original_name: res.original_name || '',
        type: res.type || 'table',
        custom_query: res.custom_query || 're',

        // 同步配置
        sync_enabled: res.sync_enabled !== false,
        sync_frequency: res.sync_frequency || 'daily',
        sync_type: res.sync_type || 'full',
        incremental_field: res.incremental_field || '',

        // 结构变更处理
        structure_change_strategy: res.structure_change_strategy || 'notify'
      })

      // 处理标签
      if (res.tags) {
        try {
          // 尝试解析JSON
          const tagsArray = JSON.parse(res.tags);
          if (Array.isArray(tagsArray)) {
            tagList.value = tagsArray;
          } else {
            // 如果不是数组，尝试作为逗号分隔的字符串处理
            tagList.value = res.tags.split(',').map(tag => tag.trim()).filter(tag => tag);
          }
        } catch {
          // 如果解析JSON失败，当作逗号分隔的字符串处理
          tagList.value = res.tags.split(',').map(tag => tag.trim()).filter(tag => tag);
        }
        formData.tags = tagList.value.join(',');
      }

      // 处理数据源对象
      await loadSourceObjects(res.data_source_id)
      if (res.type && res.original_name) {
        formData.source_object = `${res.type}:${res.original_name}`
        await loadTableColumns(res.data_source_id, res.original_name)
      }
    } catch (error) {
      console.error('获取数据集详情失败:', error)
      ElMessage.error('获取数据集详情失败: ' + (error.message || '未知错误'))
    } finally {
      formLoading.value = false
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    formLoading.value = true
    try {
      // 解析表/视图信息
      let sourceType = 'table'
      let sourceName = ''
      if (formData.source_object) {
        const parts = formData.source_object.split(':')
        if (parts.length === 2) {
          sourceType = parts[0]
          sourceName = parts[1]
        }
      }

      // 处理标签 - 转为JSON格式
      const tagsJson = JSON.stringify(tagList.value);

      // 构建提交数据
      const data = {
        name: formData.name,
        data_source_id: formData.data_source_id,
        type: sourceType,
        original_name: sourceName,
        custom_query: formData.custom_query || '',
        category: formData.category,
        tags: tagsJson,
        description: formData.description,

        // 同步配置
        sync_enabled: formData.sync_enabled,
        sync_frequency: formData.sync_frequency,
        sync_type: formData.sync_type,
        incremental_field: formData.sync_type === 'incremental' ? formData.incremental_field : '',

        // 结构变更处理
        structure_change_strategy: formData.structure_change_strategy
      }

      if (props.isAdd) {
        // 创建数据集
        const response = await createDataset(data)
        ElMessage.success('创建成功')

        // 获取新创建的数据集ID
        // FastAPI通常返回新创建的资源数据
        const newDatasetId = response.data?.id

        if (newDatasetId) {
          // 创建成功后自动同步字段
          ElMessage.info('正在同步字段，请稍候...')
          try {
            await syncDatasetFields(newDatasetId)
            ElMessage.success('字段同步成功')
          } catch (syncError) {
            console.error('同步字段失败:', syncError)
            ElMessage.warning('创建成功，但字段同步失败: ' + (syncError.response?.data?.detail || syncError.message || '未知错误'))
          }
        } else {
          console.warn('无法获取新创建的数据集ID:', response)
          ElMessage.warning('数据集创建成功，但无法自动同步字段，请手动操作')
        }
      } else {
        await updateDataset(props.datasetId, data)
        ElMessage.success('更新成功')
      }

      dialogVisible.value = false
      emit('success')
    } catch (error) {
      console.error(props.isAdd ? '创建数据集失败:' : '更新数据集失败:', error)
      ElMessage.error((props.isAdd ? '创建' : '更新') + '失败: ' + (error.response?.data?.detail || error.message || '未知错误'))
    } finally {
      formLoading.value = false
    }
  })
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 处理标签关闭
const handleTagClose = (tag) => {
  tagList.value.splice(tagList.value.indexOf(tag), 1)
  formData.tags = tagList.value.join(',')
}

// 处理标签确认
const handleTagConfirm = () => {
  if (tagInputValue.value) {
    const value = tagInputValue.value.trim()
    if (value && !tagList.value.includes(value)) {
      tagList.value.push(value)
      formData.tags = tagList.value.join(',')
    }
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 组件挂载时获取数据源列表
onMounted(async () => {
  await loadDataSources()
  if (!props.isAdd) {
    await initFormData()
  }
})
</script>

<style scoped>
.setting-hint {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.tag-input {
  width: 90px;
  margin-right: 10px;
  vertical-align: bottom;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.field-hint {
  display: block;
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
  font-style: italic;
}

:deep(.el-divider__text) {
  font-weight: bold;
  color: #409EFF;
  font-size: 14px;
}
</style>
